import { Context } from "egg";
import fs from "fs";
import * as lodash from "lodash";
import path from 'path';
import utils from "~/utils";

/**
 * 获取保存文件绝对路径
 */
export function getSaveDirAbsolutePath(ctx: Context) {
    // 统一服务静态资源保存路径
    return path.resolve(__dirname, '../');
    // return this.config.baseDir;
    // return ctx.app.config.env !== 'local' ? path.join(__dirname, "../public/") : path.join(__dirname, "../public/");
}

/**
 * 获取保存文件的相对路径
 * @param savePath
 */
export function getSaveDirRelativePath(savePath = '') {
    return path.join('/assets/', lodash.trimStart(savePath, '/'));
}

/**
 * 保存文件目录
 * @param dstPath
 */
export function getSaveFileDir(dstPath: string): string {
    return path.join(path.dirname(dstPath), '/');
}

/**
 * 读取文件
 * @param srcPath
 */
export async function readFileSync(srcPath: string): Promise<ArrayBuffer | string> {
    let regex = /^http(s):/;
    if (regex.test(srcPath)) {
        // 远程文件
        let buf = new Promise(function (resolve, reject) {
            utils.doc.getHttpData(srcPath, function (err, data) {
                if (err) {
                    return reject(err);
                }
                return resolve(data);
            });
        });
        return (await buf) as Buffer;
    } else {
        // 本地文件
        return fs.readFileSync(
            srcPath,
            "binary"
        );
    }
}

/**
 * 同步写入文件
 * @param dstPath 目标相对路径，保存至src/public/下
 * @param srcPath 源文件相对路径，可为空
 * @param delSrc 是否删除源文件
 * @param options 配置项
 */
export function writeFileSync(dstPath: string, srcPath: any = '', delSrc?: boolean, options?: { encoding?: string; mode?: number; flag?: string; }): void {
    let buffer: any = srcPath;
    if (lodash.isString(srcPath) && srcPath !== '') {
        buffer = fs.readFileSync(srcPath);
    }

    // 目标文件保存目录
    let dstDir = getSaveFileDir(dstPath);

    // 递归创建目录
    mkdirsSync(dstDir);

    if ((lodash.isString(options) && options === '') || options == null) {
        options = {
            flag: 'w',
            mode: 0o755
        };
    }
    fs.writeFileSync(dstPath, buffer, options);

    // 删除
    if (delSrc) {
        unlinkSync(srcPath);
    }
}

/**
 * 递归同步创建目录
 * @param dirName 
 * @returns 
 */
export function mkdirsSync(dirName: string) {
    if (fs.existsSync(dirName)) {
        return true;
    } else {
        if (mkdirsSync(getSaveFileDir(dirName))) {
            fs.mkdirSync(dirName, 0o755);
            return true;
        }
    }
}

/**
 * 同步删除
 * @param srcPath
 */
export function unlinkSync(srcPath: any = ''): void {
    // 删除
    if (srcPath !== '') {
        fs.unlinkSync(srcPath);
    }
}

/**
 * 获取文件后缀
 * @param filePath 
 * @returns 
 */
export function getFileExt(filePath: string) {
    return lodash.trimStart(path.extname(filePath), '.').toLowerCase();
}

/**
 * 获取文件名称
 * @param filePath
 */
export function getBaseName(filePath: string) {
    return path.basename(filePath);
}

export const IMAGE_EXT = 'jpg,jpeg,png';
export const FILE_EXT = 'doc,docx,pdf';
export const FILE_BYTE_SIZE = 2097152; // 单位（字节）2M
/**
 * 图片后缀验证
 * @param ext
 * @returns
 */
export function imageExt(ext: string): boolean {
    let extArr = IMAGE_EXT.split(',');
    return lodash.indexOf(extArr, ext.toLocaleLowerCase()) !== -1; // 存在为true
}